<template>
  <div class="main">
    <div class="user-avatar" @click="editCropper">
      <el-avatar
        class="avatara"
        :src="options.avatar"
        size="large"
        shape="square"
        title="点击上传头像"
        style="user-select: none; cursor: pointer"
      />
      <el-button class="buttona" type="primary" size="large" @click="editCropper"
        >修改头像</el-button
      >
    </div>
    <div class="eldialog">
      <el-dialog
        v-model="open"
        class="dialog"
        title="修改头像"
        width="550"
        @opened="modalOpened"
        @close="closeDialog"
      >
        <div class="cropper-img">
          <div class="cropper">
            <div>上传图像</div>
            <vue-cropper
              v-if="visible"
              ref="cropper"
              :img="options.img"
              :info="true"
              :auto-crop="true"
              :auto-crop-width="250"
              :auto-crop-height="250"
              :fixed-box="true"
              output-type="png"
              :can-move-box="false"
              :enlarge="4"
              :move-x="x"
              :move-y="y"
              @real-time="realTime"
            ></vue-cropper>
          </div>
          <!--预览效果图-->
          <div class="show-preview">
            <div>预览图像</div>
            <div :style="previews.div" class="preview">
              <img :src="previews.url" :style="previews.img" alt="" />
            </div>
          </div>
        </div>
        <div class="cropper-btns">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button size="small">
              选择
              <el-icon>
                <Upload />
              </el-icon>
            </el-button>
          </el-upload>
          &nbsp;&nbsp;&nbsp;
          <el-button size="small" @click="changeScale(1)">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button size="small" @click="changeScale(-1)">
            <el-icon>
              <Minus />
            </el-icon>
          </el-button>
          <el-button size="small" @click="rotateLeft()">
            <el-icon>
              <RefreshLeft />
            </el-icon>
          </el-button>
          <el-button size="small" @click="rotateRight()">
            <el-icon>
              <RefreshRight />
            </el-icon>
          </el-button>
          <el-button type="primary" size="small" @click="closeDialog">取消</el-button
          >&nbsp;&nbsp;&nbsp;
          <el-button type="primary" size="small" @click="uploadImg">提 交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { VueCropper } from 'vue-cropper'
import Tool from '#/utils/Tool'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '#/stores/UserInfoStore'
import { Minus, Plus, RefreshLeft, RefreshRight, Upload } from '@element-plus/icons-vue'
import Api from '#/utils/Api'
const userInfoStore = useUserInfoStore()

const userInfo = computed(() => userInfoStore.getUserInfo())
const open = ref(false) // 是否显示弹出层
const visible = ref(false) // 是否显示cropper

const options = ref({
  avatar: Tool.getAvatar(userInfo.value.userId, userInfo.value.avatar, 500),
  img: Tool.getAvatar(userInfo.value.userId, userInfo.value.avatar, 0), //裁剪图片的地址
  filename: ''
})
const previews = ref({}) // 预览对象
const cropper = ref() // cropper对象  组件引用对象
const x = ref(0)
const y = ref(0)

const file2 = ref() // 上传文件原图

// 编辑头像
const editCropper = () => {
  open.value = true
}
// 打开弹出层结束时的回调
const modalOpened = () => {
  visible.value = true
}
// 覆盖默认的上传行为
const requestUpload = () => {}
// 向左旋转
const rotateLeft = () => {
  cropper.value.rotateLeft()
}
// 向右旋转
const rotateRight = () => {
  cropper.value.rotateRight()
}
// 图片缩放
const changeScale = (num) => {
  num = num || 1
  cropper.value.changeScale(num)
}
// 上传预处理
const beforeUpload = (file) => {
  file2.value = file
  if (file.type.indexOf('image/') === -1) {
    ElMessage.error('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
  } else {
    const reader = new FileReader()
    reader.onload = () => {
      options.value.img = reader.result
      options.value.filename = file.name
    }
    reader.readAsDataURL(file)
  }
}
// 上传图片
const uploadImg = () => {
  if (file2.value === null || file2.value === undefined) {
    ElMessage.error('请先选择图片')
    return
  }

  cropper.value.getCropBlob((data) => {
    let formData = new FormData() // 请求表单
    formData.append('file', data, options.value.filename)
    formData.append('file2', file2.value)
    formData.append('userId', userInfo.value.userId)

    Api.uploadAvatar(formData).then((response) => {
      // 上传请求
      if (response.code === 200) {
        ElMessage.success(response.msg)
        // 更新登录用户的信息 头像信息
        window.ipcRenderer.send('updateUserInfoA', { type: 'avatar', data: options.value.filename })
        options.value.avatar = Tool.getAvatar(userInfo.value.userId, options.value.filename, 500)
        options.value.img = Tool.getAvatar(userInfo.value.userId, options.value.filename, 0)
        open.value = false // 关闭弹窗
      } else {
        ElMessage.error(response.msg)
      }
    })
  })
}
// 实时预览
const realTime = (data) => {
  previews.value = data
}
// 关闭窗口
const closeDialog = () => {
  options.value.img = Tool.getAvatar(userInfo.value.userId, userInfo.value.avatar, 0)
  visible.value = false
  open.value = false
}
</script>
<style scoped lang="scss">
.user-avatar {
  display: flex;
  justify-content: center;
  align-items: center;
  .avatara {
    width: 100px;
    height: 100px;
    margin-right: 30px;
  }
}

.cropper-img {
  display: flex;
  height: 280px;
  .cropper {
    width: 250px;
    height: 250px;
  }
}
.cropper-btns {
  display: flex;
  margin-top: 15px;
}

.show-preview {
  margin-left: 15px;
  display: flex;
  display: -webkit-flex;
  justify-content: center;
  flex-direction: column;
  .preview {
    overflow: hidden;
    border: 1px solid rgba(255, 255, 255, 0.4);
    background: #cccccc;
  }
}
:deep(.el-dialog) {
  margin-top: 50px;
  .el-dialog__header {
    padding: 0;
  }
}
</style>
